// Copyright 2009 Vladimir Solomenchuk
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package net.aramzamzam.tapestry.judo.mixins;

import net.aramzamzam.tapestry.judo.constants.ZoneConstants;
import net.aramzamzam.tapestry.judo.services.Require;

import org.apache.tapestry5.ClientElement;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.MarkupWriterListener;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.dom.Element;



/**
 * zone support mixin
 * usage: it can be mixed with ActionLink
 * tml
 * <t:actionlink t:id="myAction" t:mixins="dojo/zone" dojoZone="myzone">push me</t:actionlink>
 * <t:dojo.generic dojoType="dijit.ContentPane id="myzone">
 * 		<t:delegate t:to="myBlock"/>
 * 		<t:block id="myBlock">
 * 			block
 *  	</t:block>
 * </t:dojo.generic>
 * 
 * java
 * @Inject
 * private Block myBlock;
 * 
 * public Object onActionFromMyAction()
 * {
 * 	if (request.isXHR()) // in case of xhr request we will return block (component may be returned too)
 *			return myBlock;
 *	return null; //return page itself
 * }
 * 
 * @author solomenchuk
 *
 */
@Require("judo.zone")
public class ZoneSource {
	
	@Parameter(required=true, allowNull=false)
	private Object jzone;
	
	private Element componentRoot;
	
	//FIXME how to obtain root element?
	void beginRender(final MarkupWriter writer)
    {
		componentRoot=null;
		writer.addListener(new MarkupWriterListener(){
			@Override
			public void elementDidEnd(Element element) {
			}
			@Override
			public void elementDidStart(Element element) {
				componentRoot=element;
				writer.removeListener(this);
			}
		});
    }
	
	/** Ends the element. */
    void afterRender(MarkupWriter writer)
    {
    	if (componentRoot!=null)
    	{
    	    String id;
    	    if (jzone instanceof String)
    	        id=jzone.toString();
    	    else
    	        id = ((ClientElement)jzone).getClientId();
    		int idx=id.lastIndexOf('-');
    		if (idx!=-1)
    			id=id.substring(0,idx);
    		componentRoot.addClassName(ZoneConstants.ZONE_SOURCE_CSS);
    		componentRoot.addClassName(ZoneConstants.ZONE_SOURCE_CSS+"-"+id);
    	}
    }
}
